import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import iView from 'iview'
import { setToken, canTurnTo, setTitle } from '@/libs/util'
import config from '@/config'
import Cookies from 'js-cookie';
import api from "@/api/login";
const { homeName } = config

Vue.use(Router);
const router = new Router({
  base: '/CUS/',
  mode: 'hash',
  routes,
  scrollBehavior (to, from, savedPosition) {
    document.getElementById('content').scrollTo(0, 0);
  }
});
const LOGIN_PAGE_NAME = '/login';

let isInit = false;

router.beforeEach(async (to, from, next) => {
  iView.LoadingBar.start();
  if (!isInit && to.name !== 'login') {
    try {
      let { data } = await api.getUserInfo()
      if (data.returnCode === 200) {
        store.commit('user/setUserInfo', data.returnData)
      }
      isInit = true;
    } catch (e) {
      next({
        name: 'login'
      });
    }
  }
  const token = Cookies.get('token');
  if (!token && to.name !== 'login') {
    next({
      name: 'login'
    });
  } else if (token && to.name === 'login') { // 判断是否已经登录且前往的页面不是登录页
    next({
      name: 'home'
    });
    iView.LoadingBar.finish();
  } else {
    next();
  }
});

// 解决多次点击导航栏报错
const originalPush = Router.prototype.push;
Router.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
};

router.afterEach(to => {
  iView.LoadingBar.finish();
});

export default router
